package cn.xchats.onlinetraffic.common.other.http.java;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/*
 *
 *@author teddy
 *@date 2018/4/19
 */
public class DownLoadUtil {

    //保存图片
    public static void saveData(InputStream is, File file) {
        try (BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(
                     new FileOutputStream(file));) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //下载图片
    public static void downLoadImg(String url, String savePath) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                saveData(inputStream, new File(savePath));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getDesktopPath() {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        //获取桌面路径
        String upurl = fsv.getHomeDirectory().toString();
        return upurl;
    }
}
